<template>
  <div>
    <el-row>
      <el-col :span="4">
        <div class="ant-layout-sider ant-layout-sider-dark" style="">
          <div class="ant-layout-sider-children">
            <div class="united_r" style="padding: 0px 6px;">
              <div class="total_info">
                <div class="clear_float">
                  <div class="pull fs_15 bold">
                    <span>共计关联{{ singleInfo.rooms.length + singleInfo.reserveCount }}个房间</span>
                  </div>
                </div>
              </div>
              <div class="line" style="margin-left: 0px;"></div>
              <!-- 接待房间-->
              <div class=" clear_float" v-if="singleInfo.reserve == false" :class="sign == 3 ? 'select' : ''" style="line-height: 32px; padding: 0px 10px 0px 0px; border: 1px solid transparent;margin-bottom: 5px;">
                <div class="pull fs_15 bold row">
                  <i @click="receptionVisible = !receptionVisible" :class="receptionVisible ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
                    style="cursor: pointer;"></i>
                  <span>接待({{ singleInfo.rooms.length }}间)</span>
                </div>
                <div class="push fs_12 blue_color1 row" style="cursor: pointer;" @click="allRoomClick">合计 ¥ {{ countMoney.toFixed(2) }}</div>
              </div>
              <div class="cell_check_group" v-if="singleInfo.reserve == false">
                <div class="ant-checkbox-group" v-if="receptionVisible">
                  <el-checkbox-group v-model="checkList" @change="getSingleInfo">
                    <el-checkbox label="1">正常入住</el-checkbox>
                    <el-checkbox label="2">未结退房</el-checkbox>
                    <el-checkbox label="0">已结退房</el-checkbox>
                    <el-checkbox label="3">联房退房</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
              <div style="overflow-y: auto;max-height: 60vh;padding-right: 8px;" class="scrollbar" v-if="receptionVisible || singleInfo.reserve">
                <div class="cell_info" v-for="(item, index) in singleInfo.rooms" :key="item.id">
                  <div class="row clear_float" :class="item.checked ? 'select' : ''">
                    <div class="pull fs_15 bold">
                      <span class="verticalAlign">{{ item.roomSign }}{{ item.roomNum }} ({{ item.cohabitants.length }}人)</span>
                    </div>
                    <div class="push" style="cursor: pointer;" @click="item.foldSwitch = !item.foldSwitch">
                      <i :class="item.foldSwitch ? 'el-icon-caret-bottom' : 'el-icon-caret-left'"></i>
                    </div>
                    <div class="push fs_12 blue_color1" style="cursor: pointer;margin-right: 6px;" @click="roomClick(item)"
                      v-if="item.cohabitants.length > 1">同住汇总</div>
                  </div>
                  <div v-if="item.foldSwitch" class="row clear_float cursor" v-for="(po, poIndex) in item.cohabitants"
                    @click="cursorClick(po)" :class="po.checked ? 'select' : ''" :key="po.id">
                    <div class="pull" style="overflow: hidden;text-overflow: ellipsis;height: 35px;">
                      <span class="icon_oval green_bg" v-if="po.state == 1">正常入住</span>
                      <span class="icon_oval gray_bg2" v-if="po.state == 2">未结退房</span>
                      <span class="icon_oval gray_bg2" v-if="po.state == 0">已结退房</span>
                      <span class="icon_oval gray_bg2" v-if="po.state == 3">联房退房</span>
                      <span class="booking_circle_span orange_color verticalAlignUnset" v-if="po.mainSheet == 1" style="margin-left: 4px;">主</span>
                      <span :class="po.mainSheet == 1 ? 'bold' : ''" style="margin-left: 0px;">{{ po.name }}</span>
                    </div>
                    <div class="push" :class="po.mainSheet == 1 ? 'bold' : ''">￥ {{ po.state == 1 ? (po.payment + po.deposit - po.consumption).toFixed(2) : 0 }}
                      <label class="el-icon-close" v-if="po.mainSheet != 1 && po.isRoomMain != 1" @click="removePeopleBtn(po)"
                        style="color: #1890ff;margin-left: 2px;cursor: pointer;"></label></div>
                  </div>
                </div>
              </div>
              <!-- 预定房间-->
              <div v-if="singleInfo.reserveRooms.length > 0" class=" clear_float" style="line-height: 32px; padding: 0px 10px 0px 0px; border: 1px solid transparent;">
                <div class="pull fs_15 bold row">
                  <i @click="reserveVisible = !reserveVisible" :class="reserveVisible ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
                    style="cursor: pointer;"></i>
                  <span>预定({{ singleInfo.reserveCount }}间)</span>
                </div>
                <!-- <div class="push fs_12 blue_color1 row" style="cursor: pointer;" @click="allRoomClick">合计 ¥ {{ countMoney.toFixed(2) }}</div> -->
              </div>

              <div style="overflow-y: auto;max-height: 60vh;" v-if="reserveVisible && singleInfo.reserveRooms.length > 0">
                <div class="cell_info">
                  <div class="row clear_float cursor" v-for="(po, poIndex) in singleInfo.reserveRooms" @click="cursorClick(po)"
                    :class="po.checked ? 'select' : ''" :key="po.id">
                    <div class="pull" style="overflow: hidden;text-overflow: ellipsis;height: 35px;">
                      <span class="icon_oval blue_bg1" v-if="po.state == 4">预定中</span>
                      <span class="icon_oval blue_bg1" v-if="po.state == 5">取消</span>
                      <span class="icon_oval blue_bg1" v-if="po.state == 6">完成</span>
                      <span style="margin-left: 0px;">{{ po.name }}</span>
                    </div>
                    <div class="push">{{ po.tel}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="20">
        <el-tabs v-model="type" @tab-click="handleClick2">
          <el-tab-pane v-if="currItem.state == 4 || currItem.state == 5" label="详单" name="1">
            <reserveIndex ref="reserveIndex" @refreClosing="unRoom" @viewCurrInfoOrder="viewCurrInfoOrderBtn"></reserveIndex>
          </el-tab-pane>
          <el-tab-pane v-else label="详单" name="1">
            <specifications ref="specifications" v-if="sign == 1" :type="printType" @refreClosing="unRoom"></specifications>
            <roomSpecification ref="roomSpecification" v-if="sign == 2 || sign == 3" :type="printType" @refreClosing="unRoom"></roomSpecification>


          </el-tab-pane>
          <el-tab-pane label="财务" name="2">
            <finance :type="printType" ref="finance"></finance>
          </el-tab-pane>
          <el-tab-pane label="日志" name="3"></el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import moment from 'moment';
  import specifications from './specifications';
  import roomSpecification from './roomSpecification';
  import finance from './finance';
  import reserveIndex from './reserve/index';
  export default {
    data() {
      return {
        jiu: {
          type1: {
            data1: {},
            data2: {}
          },
          type2: {
            data1: {},
            data2: {}
          }
        },
        sign: 1,
        reserveVisible: true,
        receptionVisible: true,
        countMoney: 0,
        checkList: [],
        printType: '1',
        singleId: '',
        singleInfo: {},
        type: '1',
        singleSocket: null,
        currItem: {
          state: 1
        }
      };
    },
    components: {
      specifications,
      finance,
      roomSpecification,
      reserveIndex
    },
    activated() {
      var p = JSON.parse(this.$cookie.get('accounting'));
      this.singleId = p.singleId;
      this.getWebSocketInfo();
      this.type = p.type;
      //告知组件打印登记单
      this.init();
      if (p.printFlag == 1) {
        setTimeout(() => {
          this.$nextTick(() => {
            this.$refs.finance.print(p.printFlag);
          });
        }, 500);
      }
      console.log(p);
      //将第一次打印给屏蔽
      var p2 = {
        singleId: p.singleId,
        type: p.type,
        printFlag: 2,
      };
      this.$cookie.set('accounting', JSON.stringify(p2));
    },
    methods: {
      viewCurrInfoOrderBtn(floorRoomId) {
        this.singleInfo.rooms.forEach(room => {
          room.cohabitants.forEach(po => {
            if (po.floorRoomId == floorRoomId) {
              this.cursorClick(po);
              return
            }
          })
        })
      },
      unRoom() {
        var p = JSON.parse(this.$cookie.get('accounting'));
        this.singleId = p.singleId;
        this.type = p.type;
        this.$nextTick(() => {
          var that = this
          setTimeout(() => {
            that.init();
          }, 10)
        });
        console.log(p);
      },
      cursorClick(po) {
        // if(type == 1){
        //   this.currItem = po;
        //   if (!po.checked) {
        //     this.singleInfo.rooms.forEach(item => {
        //       //剔除所有房间选中
        //       item.checked = false;
        //       for (var i = 0; i < item.cohabitants.length; i++) {
        //         var pop = item.cohabitants[i];
        //         if (pop.checked) {
        //           pop.checked = false;
        //         }
        //       }
        //     });
        //     po.checked = true;
        //   }
        //   this.sign = 1;
        //   const that = this;
        //   this.$nextTick(() => {
        //     that.$refs.specifications.init(po);
        //     that.$refs.finance.init(po);
        //   });
        // }
        // else if(type == 2){

        // }

        this.currItem = po;

        if (!po.checked) {
          //剔除所有在住用户选中
          this.singleInfo.rooms.forEach(item => {
            //剔除所有房间选中
            item.checked = false;
            for (var i = 0; i < item.cohabitants.length; i++) {
              var pop = item.cohabitants[i];
              if (pop.checked) {
                pop.checked = false;
              }
            }
          });
          //剔除所有预定用户选中
          this.singleInfo.reserveRooms.forEach(item => {
            //剔除所有房间选中
            if (item.checked) {
              item.checked = false;
            }
          });
          po.checked = true;
        }

        //在住单
        if (po.state < 4) {
          this.sign = 1;
          const that = this;
          this.$nextTick(() => {
            setTimeout(() => {
              that.$refs.specifications.init(po);
              that.$refs.finance.init(po);
            }, 10)
          });
        } else {
          this.sign = 1;
          const that = this;
          this.$nextTick(() => {
            setTimeout(() => {
              that.$refs.reserveIndex.init(po);
              that.$refs.finance.init(po);
            }, 10)
          });
        }
      },
      init() {
        this.getSingleInfo();
      },
      removePeopleBtn(po) {
        this.$confirm('此操作将删除该同住, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          this.$http({
            url: this.$http.adornUrl(
              `/hotel/thotelfloorroomcheckinsingle/removePeople`
            ),
            method: "get",
            params: this.$http.adornParams({
              peopleId: po.id
            }),
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.unRoom();
              this.$message({
                message: this.$t("Common.OperationSuccessful"),
                type: "success",
                duration: 1500,
                onClose: () => {

                },
              });
            } else {
              this.$message.error(data.msg);
            }

          });

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      handleClick2(tab, res) {
        var index = tab.index;
        this.printType = parseInt(tab.index) + 1;
        const that = this;
        if (this.sign == 1) {
          if (index == 0) {
            this.$nextTick(() => {
              this.$refs.specifications.init(this.currItem);
            });
          }
          if (index == 1) {
            this.$nextTick(() => {
              this.$refs.finance.init(this.currItem);
            });
          }
        } else if (this.sign == 2) {
          if (index == 0) {
            this.$nextTick(() => {
              that.$refs.roomSpecification.init2(this.jiu.type1.data2);
            });
          }
          if (index == 1) {
            this.$nextTick(() => {
              that.$refs.finance.init2(this.jiu.type1.data1);
            });
          }
        } else {
          if (index == 0) {
            this.$nextTick(() => {
              that.$refs.roomSpecification.init2(this.jiu.type2.data2);
            });
          }
          if (index == 1) {
            this.$nextTick(() => {
              that.$refs.finance.init2(this.jiu.type2.data1);
            });
          }
        }
      },
      roomClick(roomInfo) {
        if (!roomInfo.checked) {
          this.singleInfo.rooms.forEach(item => {
            //剔除所有房间选中
            item.checked = false;
            //剔除所有子同住
            for (var i = 0; i < item.cohabitants.length; i++) {
              var pop = item.cohabitants[i];
              if (pop.checked) {
                pop.checked = false;
              }
            }
          });
          roomInfo.checked = true;
        }
        this.sign = 2;
        const that = this;
        this.jiu.type1.data1 = {
          roomIds: roomInfo.id,
          singleId: roomInfo.singleId
        };
        this.jiu.type1.data2 = {
          roomIds: roomInfo.id,
          type: 2,
          singleId: roomInfo.singleId
        };
        this.$nextTick(() => {
          that.$refs.finance.init2(this.jiu.type1.data1);
          that.$refs.roomSpecification.init2(this.jiu.type1.data2);
        });
      },
      allRoomClick() {
        var arr = [];
        var singleId = '';
        this.singleInfo.rooms.forEach(item => {
          singleId = item.singleId;
          arr.push(item.id);
          //剔除所有房间选中
          item.checked = false;
          //剔除所有子同住
          for (var i = 0; i < item.cohabitants.length; i++) {
            var pop = item.cohabitants[i];
            if (pop.checked) {
              pop.checked = false;
            }
          }
        });
        this.sign = 3;
        this.jiu.type2.data1 = {
          roomIds: arr.join(","),
          singleId: singleId
        };
        this.jiu.type2.data2 = {
          roomIds: arr.join(","),
          type: 3,
          singleId: singleId
        };
        this.$nextTick(() => {
          this.$refs.roomSpecification.init2(this.jiu.type2.data2);
          this.$refs.finance.init2(this.jiu.type2.data1);
        });
      },
      getSingleInfo() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinsingle/single/${this.singleId}`),
          method: 'get',
          params: this.$http.adornParams({
            types: this.checkList.join(',')
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.singleInfo = data.tHotelFloorRoomCheckinSingle;
            //默认选中第一个
            this.$nextTick(() => {
              if (this.singleInfo.rooms && this.singleInfo.rooms.length > 0) {
                if (this.singleInfo.rooms[0].cohabitants.length > 0) {
                  this.cursorClick(this.singleInfo.rooms[0].cohabitants[0]);
                }
              } else {
                if (this.singleInfo.reserveRooms && this.singleInfo.reserveRooms.length > 0) {
                  this.cursorClick(this.singleInfo.reserveRooms[0]);
                }
              }
            });
            this.countMoney = 0;
            //计算金额
            if (this.singleInfo.rooms && this.singleInfo.rooms.length > 0) {
              this.singleInfo.rooms.forEach(item => {
                item.cohabitants.forEach(i => {
                  if (i.state == 1 || i.state == 2) {
                    this.countMoney += (parseFloat(i.payment) + parseFloat(i.deposit)) - parseFloat(i.consumption);
                  }
                });
              });
            }
          }
        });
      },
      //WebSocket sellerSign 商家标识
      webSocketInit(sellerSign) {
        if (typeof WebSocket === "undefined") {
          alert("您的浏览器不支持socket");
        } else {
          let domain =
            window.SITE_CONFIG["baseUrl"].indexOf("https") > 0 ?
            window.SITE_CONFIG["baseUrl"].replace(/https/g, "wss") :
            window.SITE_CONFIG["baseUrl"].replace(/http/g, "ws");

          // 实例化socket
          this.singleSocket = new WebSocket(`${domain}/websocket/${sellerSign}`);
          // 监听socket连接
          this.singleSocket.onopen = this.webSocketOpen;
          // 监听socket错误信息
          this.singleSocket.onerror = this.webSocketError;
          // 监听socket消息
          this.singleSocket.onmessage = this.webSocketGetMessage;
        }
      },
      // 获取当前商家信息
      getWebSocketInfo() {
        this.$http({
          url: this.$http.adornUrl("/hotel/thotelfloorroomcheckinsingle/webSocket/info"),
          method: "get",
          params: this.$http.adornParams({
            singleId: this.singleId
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.webSocketInit(data.webSocketSign);
          }
        });
      },
      webSocketOpen: function() {
        console.log("详单socket连接成功");
      },
      webSocketError: function() {
        console.log("连接错误");
      },
      webSocketGetMessage: function(msg) {
        console.log("socket", msg)
        if (msg.data.indexOf('acc') != -1) {
          if (this.sign == 1) {
            this.$refs.finance.init(this.currItem);
          } else if (this.sign == 2) {
            this.$refs.finance.init2(this.jiu.type1.data1);
          } else {
            this.$refs.finance.init2(this.jiu.type2.data1);
          }
        } else {
          this.getSingleInfo()
        }
      },
      send: function() {
        this.singleSocket.send(this.params);
      },
      close: function() {
        console.log("socket已经关闭");
      }
    },
    destroyed() {
      this.close()
      console.log('详单socket实例销毁完成');
    }
  };
</script>
<style>
  @import url('./accounting.css');

  .cell_check_group .el-checkbox:nth-child(2n) {
    margin-right: 0px !important;
    margin-left: 0px !important;
  }

  .cell_check_group .el-checkbox:nth-child(1n) {
    margin-right: 30px;
    margin-left: 0px;
  }

  .blue_color1 {
    color: #1890ff;
  }

  .scrollbar::-webkit-scrollbar {
    width: 5px !important;
    height: 5px !important;
    background-color: #606266;
  }

  ::-webkit-scrollbar-track {
    background-color: #f0f0f0;
  }

  /* 滚动条的滑轨背景颜色 */

  ::-webkit-scrollbar-thumb {
    background-color: #606266;
  }

  /* 滑块颜色 */

  ::-webkit-scrollbar-button {
    display: none;
  }

  /* 滑轨两头的监听按钮颜色 */
</style>

<style lang="less" scoped>
  .el-row {
    /deep/ .el-col.el-col-20 {
      padding-left: 10px;
    }
  }
</style>
